package com.thinkgem.jeesite.modules.weixin.checkrequestisfromwechat;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 开发者通过检验signature对请求进行校验（下面有校验方式）。若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。加密/校验流程如下：
 * 1.将token、timestamp、nonce三个参数进行字典序排序
 * 2.将三个参数字符串拼接成一个字符串进行sha1加密
 * 3.开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
 * Created by yangrui on 2018/4/1.
 */
@Slf4j
@Controller
public class CheckRequestFromWeChatController {

    @RequestMapping("/checkRequestIsFromWeChat")
    private void checkRequestFromWeChat(CheckRequestFromWeChatEntity entity, HttpServletResponse response){
        try {
            if (CheckUtils.checkSignature(entity)) {
                PrintWriter out = response.getWriter();
                out.print(entity.getEchostr());
                out.close();
            } else {
                log.debug("请求不是来源于微信！");
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.debug(e.getMessage());
        }
    }
}
